package com.zeroup.auto.window;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.AppOpsManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Process;
import android.provider.Settings;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.ven.assists.Assists;
import com.zeroup.auto.R;
import com.zeroup.auto.assists.next.NextStepBean;
import com.zeroup.auto.assists.step.dy.StartStep;
import com.zeroup.auto.assists.step.unify.ScreenRollingStep;
import com.zeroup.auto.service.UpdateApkService;
import com.zeroup.auto.socket.WebSocketJb;
import com.zeroup.auto.utils.AssistsUtils;
import com.ven.assists.stepper.StepManager;


import org.kymjs.kjframe.ui.AnnotateUtil;
import org.kymjs.kjframe.ui.BindView;

import java.util.ArrayList;
import java.util.List;

public class FloatService extends Service implements View.OnClickListener{
    View btnView;
    WindowManager windowManager;
    WindowManager.LayoutParams params;
    Boolean isAdded;
    public static String OPERATION = "是否需要开启";
    public static int OPERATION_SHOW = 1;
    public static int OPERATION_HIDE = 2;
    int HANDLE_CHECK_ACTIVITY = 0;

    int auto = 1;

    @BindView(id= R.id.close_float_window,click = true)
    Button close_float_window;

    @BindView(id=R.id.start_dy,click = true)
    Button start_dy;

    @BindView(id=R.id.printTextView)
    TextView printTextView;

    @BindView(id=R.id.scrollview)
    ScrollView scrollview;


    private String user_id = "";

    private String sbh = "";

    WebSocketJb webSocketJb;



    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        int operation = intent.getIntExtra(OPERATION, 3);
        this.user_id = intent.getStringExtra("uid");
        this.sbh = intent.getStringExtra("sbh");
        if (operation == OPERATION_SHOW) {
            mHandler.sendEmptyMessage(HANDLE_CHECK_ACTIVITY);
        } else if (operation == OPERATION_HIDE) {
            mHandler.removeMessages(HANDLE_CHECK_ACTIVITY);
        }
        this.startDy();
        return super.onStartCommand(intent, flags, startId);
    }

    private void createrWebSocket(){
        webSocketJb = new WebSocketJb(mHandler);
        webSocketJb.startWebSocket(this.user_id,sbh);
    }

    @Override
    public void onCreate() {
        createWindowView();
        super.onCreate();
    }

    @SuppressLint("ClickableViewAccessibility")
    private void createWindowView() {
        btnView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.float_service, null);
        AnnotateUtil.initBindView(this,btnView);
        windowManager = (WindowManager) getApplicationContext()
                .getSystemService(Context.WINDOW_SERVICE);
        params = new WindowManager.LayoutParams();

        // 设置悬浮框不可触摸
        params.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        // 悬浮窗不可触摸，不接受任何事件,同时不影响后面的事件响应
        params.format = PixelFormat.RGBA_8888;
        // 设置悬浮框的宽高
        params.width = WindowManager.LayoutParams.WRAP_CONTENT;
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
//        params.gravity = Gravity.START | Gravity.BOTTOM;
        params.gravity = Gravity.LEFT | Gravity.BOTTOM;
        params.x = 0;
        params.y = 150;
        // 设置Window Type
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            params.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            params.type = WindowManager.LayoutParams.TYPE_PHONE;
        }
        // 设置悬浮框的Touch监听
        btnView.setOnTouchListener(new View.OnTouchListener() {
            //保存悬浮框最后位置的变量
            int lastX, lastY;
            int paramX, paramY;

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        lastX = (int) event.getRawX();
                        lastY = (int) event.getRawY();
                        paramX = params.x;
                        paramY = params.y;
                        break;
                    case MotionEvent.ACTION_MOVE:
                        int dx = (int) event.getRawX() - lastX;
                        int dy = (int) event.getRawY() - lastY;
                        params.gravity = Gravity.NO_GRAVITY;
                        params.x = paramX + dx;
                        params.y = paramY + dy;
                        // 更新悬浮窗位置
                        windowManager.updateViewLayout(btnView, params);
                        break;
                }
                return true;
            }
        });
        windowManager.addView(btnView, params);
        isAdded = true;
        printTextView.setMovementMethod(ScrollingMovementMethod.getInstance()); // 允许滚动
        printTextView.setText("");

    }

    private void printLog(String log){
        printTextView.append(log+"\n");
        scrollview.post(new Runnable() {
            @Override
            public void run() {
                scrollview.smoothScrollTo(0, printTextView.getBottom());
            }
        });
    }

    /**
     * 判断当前界面是否是桌面
     * android 6.0以上只能判断当前应用包名和Launcher
     */
    private boolean isAtHome() {
        ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> runningTaskInfos = mActivityManager.getRunningTasks(1);
        Log.d("henry", "是否在主页面" + runningTaskInfos);
        return getHomeApplicationList().contains(runningTaskInfos.get(0).topActivity.getPackageName());
    }

    /**
     * 获得属于桌面的应用的应用包名称
     *
     * @return 返回包含所有包名的字符串列表
     */

    /**
     * 获得属于桌面的应用的应用包名称
     * 返回包含所有包名的字符串列表数组
     *
     * @return
     */
    private List<String> getHomeApplicationList() {
        List<String> names = new ArrayList<String>();
        PackageManager packageManager = this.getPackageManager();
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        List<ResolveInfo> resolveInfos = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        for (ResolveInfo resolveInfo : resolveInfos) {
            names.add(resolveInfo.activityInfo.packageName);
        }
        Log.d("henry", "主屏幕应用列表" + names);
        return names;
    }

    //定义一个更新界面的Handler
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == HANDLE_CHECK_ACTIVITY) {
                Message m = new Message();
                m.what = 2;
                mHandler.sendMessage(m);
            }else if (msg.what == auto) {
                NextStepBean nextStepBean = (NextStepBean) msg.obj;
                printLog("收到自动命令:"+nextStepBean.getName() +",马上执行");
                AssistsUtils.start(nextStepBean);
            }else if (msg.what == -2) {
                printLog("自定命令停止");
                AssistsUtils.stop();
            }else if (msg.what == 99) {//服务器连接成功
                String log = (String) msg.obj;
                printLog(log);
                setOpenBtn(true);
                isStart = true;
            }else if (msg.what == 100) {
                webSocketJb = null;
                setOpenBtn(false);
                String log = "服务器连接断开.";
                printLog(log);
            }else if (msg.what == 98) {//服务器连接成功
                String log = (String) msg.obj;
                printLog(log);
            }else if (msg.what == 97) {//更新app
                String downloadUrl = (String) msg.obj;
                Intent updateServiceIntent = new Intent(getApplicationContext(), UpdateApkService.class);

                updateServiceIntent.putExtra("downloadUrl",downloadUrl);
                startService(updateServiceIntent);
            }
        }
    };

    @Override
    public void onDestroy() {
        if (isAdded) {
            windowManager.removeView(btnView);
        }
        mHandler.removeCallbacksAndMessages(null);
        windowManager = null;
        mHandler = null;
        super.onDestroy();
    }

    public void close_float_window(View view){
        if (isAdded) {
            stopSelf();
            if(webSocketJb!=null){
                webSocketJb.closeWebSocket();
            }
        }
        Toast.makeText(FloatService.this, "悬浮框已关闭~", Toast.LENGTH_SHORT).show();
    }

    /**
     * 验证权限
     */
    private boolean validPer(){
        if (Assists.INSTANCE.isAccessibilityServiceEnabled()) {
//            StepManager.INSTANCE.execute(WxStep.class,1,0,null,false);
//            floatingWindowManager.showFloatingWindow();
//            Context context = this.getApplication().getApplicationContext();
//            AppOpsManager appOpt =(AppOpsManager)context.getSystemService(Context.APP_OPS_SERVICE);
//            int mode = appOpt.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, Process.myUid(),context.getPackageName());
//            boolean isGranted=mode == AppOpsManager.MODE_ALLOWED;
//            if (isGranted) {
//
//            } else {
//                // 没有权限，需要引导用户去设置中手动开启
//                Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
//                startActivity(intent);
//            }
            return true;
        } else {
            Assists.openAccessibilitySetting();
            return false;
        }

    }

    public void startDy(){
        if(!validPer()){
            return;
        }
        if(webSocketJb ==null || !webSocketJb.isClient){
//            StepBeanData stepBeanData = new StepBeanData();
//            stepBeanData.setDataValue("回力");
//            NextStepBean searchNextStepBean = new NextStepBean("执行搜索",TopSearchStep.class.getName(),3,2000,null,null);
//            NextStepBean inputNextStepBean = new NextStepBean("输入搜索关键字",TopSearchStep.class.getName(),2,2000,stepBeanData,searchNextStepBean);
//            NextStepBean clickSearchBtn = new NextStepBean("滑动", ScreenRollingStep.class.getName(),1,3000,null,null);
//            NextStepBean startDy = new NextStepBean("启动", StartStep.class.getName(),1,0,null,clickSearchBtn);
//            Log.d("===>",JSON.toJSONString(startDy, SerializerFeature.WriteClassName));
//        StepData stepData = new StepData();
//        stepData.setData(clickSearchBtn);
//        StepManager.INSTANCE.execute(WxStep.class,1,0,null,true);
//            AssistsUtils.start(startDy);
            setOpenBtn(true);
            isStart = true;
            createrWebSocket();
            printLog("启动自动监听:成功");
        }else{
            setOpenBtn(false);
            StepManager.INSTANCE.setStop(true);
            isStart = false;
            webSocketJb.closeWebSocket();
            webSocketJb = null;
            printLog("停止自动监听:成功");
        }
    }

    private void setOpenBtn(boolean isStart){
        if(isStart){
            int bottom = start_dy.getPaddingBottom();
            int top = start_dy.getPaddingTop();
            int right = start_dy.getPaddingRight();
            int left = start_dy.getPaddingLeft();
            int width = start_dy.getWidth();
            int height = start_dy.getHeight();
            start_dy.setText(R.string.start_stop_txt);
            start_dy.setBackgroundResource(R.color.colorFs);
            start_dy.setWidth(width);
            start_dy.setHeight(height);
            start_dy.setPadding(left, top, right, bottom);
        }else{
            int bottom = start_dy.getPaddingBottom();
            int top = start_dy.getPaddingTop();
            int right = start_dy.getPaddingRight();
            int left = start_dy.getPaddingLeft();
            int width = start_dy.getWidth();
            int height = start_dy.getHeight();
            start_dy.setText(R.string.start_dy_txt);
            start_dy.setBackgroundResource(R.color.colorAccent);
            start_dy.setWidth(width);
            start_dy.setHeight(height);
            start_dy.setPadding(left, top, right, bottom);
        }
    }

    public static boolean isStart = false;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.start_dy:
                this.startDy();
                break;
            case R.id.close_float_window:
                this.close_float_window(v);
                break;
        }
    }
}

